package ru.compscicenter.uno.net;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.SocketTimeoutException;
import java.util.TreeSet;

public class UDPClient {
    private int port = UDPServer.PORT;
    private final String BROADCAST_ADDRESS = UDPServer.BROADCAST_ADDRESS;
    private MulticastSocket socket;
    private int timeLimit = 500;
    private static InetAddress group;

    public UDPClient() throws IOException {
        socket = new MulticastSocket(port);
        socket.setSoTimeout(timeLimit);
        group = InetAddress.getByName(BROADCAST_ADDRESS);
        socket.joinGroup(group);
    }

    public TreeSet<String> findServers() throws IOException {
        TreeSet<String> servers = new TreeSet<String>();

        byte[] buff = new byte[100];

        DatagramPacket packet = new DatagramPacket(buff, buff.length);

        long startTime = System.currentTimeMillis();

        while (System.currentTimeMillis() - startTime < timeLimit) {
            try {
                socket.receive(packet);
            } catch (SocketTimeoutException e) {
                break;
            }
            String message = new String(packet.getData());

            if (message.startsWith(UDPServer.BROADCAST_MESSAGE)) {
                String[] temp = message.split(" ");
                servers.add(temp[4] + ":" + temp[6]);
            }
        }
        return servers;
    }
}
